//以products.xml作为基础，实现客户购买的方法，
//输入商品号和购买数量，计算应付金额，如果是折扣商品，打七折；
//如果购买数量超过库存量，给出提示；商品不存在，给出提示；
//购买成功，扣除相应的数量。最后输出应付款的金额。
package XML作业;

import java.io.File;
import java.io.FileWriter;
import java.util.List;
import java.util.Scanner;

import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;

public class ZuoYe4 {
	public static void main(String[] args) throws Exception {
		Scanner in = new Scanner(System.in);
		System.out.println("请输入商品号");
		String num = in.next();
		String s1 = "/product[itemno=" + num + "]";
		System.out.println("请输入购买数量");
		double shuliang = in.nextDouble();
		SAXReader reader = new SAXReader();
		Document doc = reader.read(new File("products.xml"));
		List<Element> list = doc.selectNodes("/shop" + s1);
//		System.out.println(list.size());
		if (list.size() == 0) {
			System.out.println("商品不存在");
			return;
		}
		double money;
		for (Element e : list) {
			double price = Double.parseDouble(e.selectSingleNode("price").getText());
//			System.out.println(price);
			double stockcount = Double.parseDouble(e.selectSingleNode("stockcount").getText());
//			System.out.println(stockcount);
			String discount = e.attributeValue("discount");
//			System.out.println(discount);
			if (e.selectSingleNode("itemno").getText().equals(num) && shuliang <= stockcount
					&& discount.equals("false")) {
				money = price * shuliang;
				System.out.println(money + "元");
				stockcount -= shuliang;
				OutputFormat format = OutputFormat.createPrettyPrint();
				format.setEncoding("UTF-8");
				XMLWriter xm = new XMLWriter(new FileWriter("products.xml"), format);
				xm.write(doc);
				xm.close();

			} else if (e.selectSingleNode("itemno").getText().equals(num) && shuliang <= stockcount
					&& discount.equals("true")) {
				money = (price * shuliang) * 0.7;
				System.out.println(money + "元");
				stockcount -= shuliang;
				OutputFormat format = OutputFormat.createPrettyPrint();
				format.setEncoding("UTF-8");
				XMLWriter xm = new XMLWriter(new FileWriter("products.xml"), format);
				xm.write(doc);
				xm.close();

			} else if (e.selectSingleNode("itemno").getText().equals(num) && shuliang >= stockcount) {
				System.out.println("您购买的商品超过库存量");
			}
		}
	}
}